#!/usr/bin/perl

# Regenerates (or generates) /etc/asterisk/musiconhold.conf. 
# Released under the GPL V2. (C) Rob Thomas rob@wpm4L.com

use DBI;

open(FILE, "/etc/amportal.conf") || die "Failed to open amportal.conf\n";
while (<FILE>) {
    chomp;                  # no newline
    s/#.*//;                # no comments
    s/^\s+//;               # no leading white
    s/\s+$//;               # no trailing white
    next unless length;     # anything left?
    my ($var, $value) = split(/\s*=\s*/, $_, 2);
    $User_Preferences{$var} = $value;
} 
close(FILE);

# the name of the box the MySQL database is running on
$hostname = $User_Preferences{"AMPDBHOST"};
# the name of the database our tables are kept
$database = $User_Preferences{"AMPDBNAME"};
# username to connect to the database
$username = $User_Preferences{"AMPDBUSER"};
# password to connect to the database
$password = $User_Preferences{"AMPDBPASS"};

$dbh = DBI->connect("dbi:mysql:dbname=$database;host=$hostname", "$username", "$password");
$q=$dbh->prepare("select value from globals where variable=?");
$q->execute("MOH_COMMAND");
if ($q->rows == 0) {
	# We haven't been configured. Don't touch anything and walk away
	# quietly.
	exit 0;
} else {
	my ($mohcmd) = $q->fetchrow_array;
	if ($mohcmd eq "mpg123") {
		$moh = "default => quietmp3:/var/lib/asterisk/mohmp3";
	} else {
		$q->execute("MOH_VOLUME");
		my ($atten) = $q->fetchrow_array;
		$moh = "/usr/local/bin/madplay --mono -R 8000 -a$atten --output=raw:-";
	}
}

# Generate the new musiconhold.conf

unlink ("/etc/asterisk/musiconhold.conf");
open (MOH, ">/etc/asterisk/musiconhold.conf");
print MOH "; Musiconhold.conf Autogenerated by gen_moh.pl\n";
print MOH "; This will be automatically overwritten while the MOH_COMMAND entry\n";
print MOH "; exists in the global table.\n";
# print MOH "[default]\nmode=custom\ndirectory=/var/lib/asterisk/mohmp3\napplication=$moh\n";
print MOH "[default]\nmode=files\ndirectory=/var/lib/asterisk/mohmp3\nrandom=yes\n";
print MOH "#include musiconhold_additional.conf\n";
close MOH;

